import React, { PropTypes, Component } from 'react';
import SubMenu from './SubTree'

class MenuItem extends Component {

  constructor (props) {
    super(props)
  }

  static propTypes = {
    data: React.PropTypes.object.isRequired,
    active: React.PropTypes.bool
  }

  _getMenuIndent () {
    let indents = []

    if (this.props.level) {
      for (let i = 0; i < this.props.level; i++) {
        indents.push(<span key={i} className="tree-indent"></span>)
      }
    }

    return indents
  }

  render() {
    let item = this.props.data
    let ifFirst = this.props.active
    let iconClass = `glyphicon glyphicon-${item.iconCls || 'option-vertical'}`
    let hasSub = !!item.children.length

    return (
      <li className={cx({active: ifFirst, open: ifFirst && hasSub, 'has-sub': hasSub})} onClick={this._onClick}>
        <a href={(hasSub) ? 'javascript: void 0;' : ('#' + (item.src || ''))}>
          {this._getMenuIndent()}
          {this.props.checkable && <input className="tree-node-ckb" type="checkbox" data-id={item.id} onClick={this.props.onCKBClick} />}
          <span className={iconClass}></span>
          {item.text}
          {hasSub && <span className="icon glyphicon glyphicon-menu-left pull-right"></span>}
        </a>
        {hasSub && <SubMenu checkable={this.props.checkable} onCKBClick={this.props.onCKBClick} level={this.props.level ? (this.props.level + 1) : 1} list={item.children} />}
      </li>
    )
  }

  _onClick (e) {
    e.stopPropagation()
    let $target = $(e.currentTarget)
    $target.addClass('active').siblings().removeClass('active open').find('.sub-tree').slideUp('fast')

    if ($target.hasClass('has-sub')) {
      $target.toggleClass('open').find('.sub-tree').slideToggle('fast')
      $target.find('li').removeClass('active')
    }
  }
}

export default MenuItem

